package org.zgy.stock.threads;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.val;
import org.zgy.stock.dto.StockBaseDto;
import org.zgy.stock.utils.okhttp3.OkHttpUtil;

import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;

public class StockBaseThread implements Callable<List<StockBaseDto>> {
    private static String API_URL = "https://push2.eastmoney.com/api/qt/clist/get?fs=m%3A0%2Bt%3A6%2Cm%3A0%2Bt%3A80%2Cm%3A1%2Bt%3A2%2Cm%3A1%2Bt%3A23%2Cm%3A0%2Bt%3A81%2Bs%3A2048&fields=f12%2Cf14&fid=f3&pz=100&pn=";
    private Integer start;
    private Integer end;

    public StockBaseThread(Integer start, Integer end) {
        this.start = start;
        this.end = end;
    }
    @Override
    public List<StockBaseDto> call() throws Exception {
        List<StockBaseDto> list = new ArrayList<>();
        for (int i = start; i < end; i++) {
            String result = OkHttpUtil.getRequest(API_URL + i, null);
            JSONObject json = JSON.parseObject(result);
            if (json == null) {
                break;
            }
            JSONObject json_data = json.getJSONObject("data");
            if (json_data == null) {
                break;
            }
            JSONObject diff_json = json_data.getJSONObject("diff");
            Set<String> keys = diff_json.keySet();
            for (String key : keys) {
                val itemJson = diff_json.getJSONObject(key);
                var code = itemJson.getString("f12");
                var name = itemJson.getString("f14");
                list.add(new StockBaseDto(code, name));
            }
        }
        System.out.println(Thread.currentThread().getName() + ":" + list.size());
        return list;
    }
}
